<template>
  <div>
    <el-table
        :data="tbdata"
        style="width: 100%"
        stripe
        highlight-current-row
        height="600"
        empty-text="暂时没有数据"
    >
      <el-table-column type="selection" fixed="left"></el-table-column>
      <el-table-column label="课程编号" prop="id" sortable></el-table-column>
      <el-table-column label="课程名" prop="name" sortable align="center"></el-table-column>
      <el-table-column label="学分" prop="score" sortable align="center"></el-table-column>
      <el-table-column align="right" fixed="right" width="200">
        <template slot="header" slot-scope="scope">
          <el-select v-model="searchType" placeholder="请选择" size="mini" style="width: 90px;padding: 0;">
            <el-option value="编号"></el-option>
            <el-option value="课程"></el-option>
            <el-option value="学分"></el-option>
          </el-select>
          <el-input v-model="search" size="mini" placeholder="输入关键字搜索" style="padding: 0; width: 120px;"/>
        </template>
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">Edit</el-button>
          <el-button size="mini" type="danger" icon="el-icon-delete" circle
                     @click="handleDelete(scope.$index, scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :title="dialogType=='create'?'创建课程':'编辑课程'" :visible.sync="dialogFormVisible">
      <el-form :model="form" v-if="form">
        <el-form-item label="课程编号" :label-width="formLabelWidth">
          <el-input v-model="form.id" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="课程名" :label-width="formLabelWidth">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="学分" :label-width="formLabelWidth">
          <el-input v-model="form.score" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
            @click="
						dialogFormVisible = false;
						form = null;
					"
        >
          取 消
        </el-button>
        <el-button type="primary" @click="formConfirm">确 定</el-button>
      </div>
    </el-dialog>
    <el-button icon="el-icon-circle-plus-outline" type="primary" @click="createCourse">新建课程</el-button>
    <el-button icon="el-icon-refresh-right" type="infor" @click="getCourses"></el-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tableData: [],
      search: '',
      dialogFormVisible: false,
      form: null,
      formLabelWidth: '120px',
      dialogType: 'edit',
      searchType: '编号'
    };
  },
  mounted: function () {
    this.getCourses()
  },
  methods: {
    /**
     * 获取所有课程信息
     */
    getCourses() {
      let that = this
      that.tableData = []
      that.axios.get(that.$store.state.serverHost + '/course/getCourses/')
          .then((res) => {
            let reg = new RegExp("'", 'g');
            for (let i in res.data) {
              let data = JSON.parse(res.data[i].replace('"', '').replace(reg, '"'));
              that.tableData.push(data)
            }
            that.$store.commit('updataCourse', that.tableData)
          })
          .catch((e) => {
            console.log(e)
            that.$message.error("获取数据失败")
          })
    },
    /**
     * 点击编辑按钮触发,格式化数据，打开表单
     *
     * @param {Number} index 数据中的角标
     * @param {Object} row 数据对象
     */
    handleEdit(index, row) {
      console.log(index, row);
      let that = this;
      if (that.dialogFormVisible) return
      if (that.dialogType != 'edit') that.dialogType = 'edit'
      that.form = row
      that.dialogFormVisible = true;
    },
    /**
     * 点击删除按钮触发
     *
     * @param {Number} index 数据中的角标
     * @param {Object} row 数据对象
     */
    handleDelete(index, row) {
      console.log(index, row);
      let that = this
      that.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
          .then(() => {
            this.axios.post(that.$store.state.serverHost + '/course/deleteCourse/',
                {
                  id: row.id
                })
                .then((res) => {
                  console.log(res)
                })
                .catch((e) => {
                  console.log(e)
                })

            that.$message({
              type: 'success',
              message: '删除成功!'
            });
            setTimeout(() => {
              that.getCourses()
            }, 1000)
          });
    },
    /**
     * 表单点击提交按钮触发
     */
    formConfirm() {
      let that = this
      if (!that.form) return
      for (let key in that.form) {
        if (!that.form[key]) {
          that.$message.error(key + "不能为空")
          return
        }
      }
      if (that.dialogType == "create") {
        that.axios.post(that.$store.state.serverHost + '/course/createCourse/', that.form)
            .then((res) => {
              console.log(res);
              if(res.data==="创建成功") that.$message.success('创建成功');
              else that.$message.error(res.data)
              that.getCourses()
            })
            .catch((e) => {
              console.log(e)
            })
      } else {
        console.log("修改信息")
        that.axios.post(that.$store.state.serverHost + '/course/changeCourse/', that.form)
            .then((res) => {
              if (res.data != "修改失败") that.$message.success("修改成功")
              setTimeout(() => {
                that.getCourses()
              }, 1000)
            })
            .catch((e) => {
              console.log(e)
            })
      }
      that.dialogFormVisible = false;
      that.form = null;
    },
    /**
     * 创建课程，格式化数据，打开表单
     */
    createCourse() {
      let that = this
      if (that.dialogFormVisible) return
      if (that.dialogType != 'create') that.dialogType = 'create'
      that.form = {
        id: '',
        name: '',
        score: ''
      }
      that.dialogFormVisible = true
    }
  },
  computed: {
    tbdata() {
      let that = this
      return that.tableData.filter((data) => {
        if (!that.search) return true
        switch (that.searchType) {
          case "课程":
            return JSON.stringify(data.name).includes(that.search)
          case "学分":
            return JSON.stringify(data.score).includes(that.search)
          default:
            return JSON.stringify(data.id).includes(that.search)
        }
      })
    },
  }
};
</script>

<style scoped></style>
